package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hcb.tonguetiphealth.adapter.GeneralPageAdapter;
import com.hcb.tonguetiphealth.adapter.MemberListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.HotResPackage;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.MemberActivity;
import com.hcb.tonguetiphealth.view.MemberHomepageActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.view.ResBookActivity;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class MemberSearchWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "memberSearchWidget";
	
	private Activity ctx;
	private Handler mHandler;
	private Button btSearch;
	private LinearLayout llBack;
	private EditText etSearch;
	private LayoutInflater inflater;
	private ImageView iv, iv1, iv2, iv3, iv4, iv5, iv6;
	private int crrentPageId = 0;
//	private LinearLayout llCity, llSearch, llHotRes, llLogin, llMore ;
	private List<User>memberList = new ArrayList<User>();
	private RadioButton rbtAll, rbtName ,rbtLabel, rbtPerson, rbtRes;
	private RadioGroup radioGroup;
	private String count = "6";
	
	private ViewPager viewPager;
	private List<View> pageViews;
	private View view;
	private GeneralPageAdapter pageAdapter;
	
	private String type = "1"; //type=1  全部搜索
							   //type=2 按昵称搜索
							   //type=3按标签搜索
							   //type=4按个人搜索
							   //type=5按商家搜索
							   //type=6营养师
	
	public MemberSearchWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.member_search_widget, this); 
		
		inflater = ctx.getLayoutInflater();
		bindView();
		bindEvent();
		getHotMember();
	}
	
	private void bindView(){
		etSearch = (EditText)findViewById(R.id.et_quick_search);
		btSearch = (Button)findViewById(R.id.bt_quick_search);
		llBack = (LinearLayout)findViewById(R.id.search_linearlayout_back);
		viewPager = (ViewPager)findViewById(R.id.hot_res_viewpager);
		
		rbtAll = (RadioButton)findViewById(R.id.RadioButton_all);
		rbtName = (RadioButton)findViewById(R.id.RadioButton_name);
		rbtLabel = (RadioButton)findViewById(R.id.RadioButton_labels);
		rbtPerson = (RadioButton)findViewById(R.id.RadioButton_person);
		rbtRes = (RadioButton)findViewById(R.id.RadioButton_res);
		radioGroup = (RadioGroup)findViewById(R.id.RadioGroup01);
		
		rbtAll.setChecked(true);
		
//		llCity = (LinearLayout)findViewById(R.id.linearlayout_home_city);
//		llSearch = (LinearLayout)findViewById(R.id.linearlayout_home_search);
//		llHotRes = (LinearLayout)findViewById(R.id.linearlayout_home_res);
//		llLogin = (LinearLayout)findViewById(R.id.linearlayout_home_login);
//		llMore = (LinearLayout)findViewById(R.id.linearlayout_home_more);
	}
	
	private void bindEvent(){
		
//		llCity.setOnClickListener(this);
//		llSearch.setOnClickListener(this);
//		llHotRes.setOnClickListener(this);
//		llLogin.setOnClickListener(this);
//		llMore.setOnClickListener(this);
//		
		btSearch.setOnClickListener(this);
		llBack.setOnClickListener(this);
		
		
		  /* 设置事件监听  */  
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {  
            @Override  
            public void onCheckedChanged(RadioGroup group, int checkedId)  
            {  
                switch (checkedId) {
					case R.id.RadioButton_all:
						type = "1";
						break;
					case R.id.RadioButton_name:
						type = "2";
						break;
					case R.id.RadioButton_labels:
						type = "3";
						break;
					case R.id.RadioButton_person:
						type = "4";
						break;
					case R.id.RadioButton_res:
						type = "5";
						break;
					case R.id.RadioButton_yys:
						type = "6";
						break;
					default:
						break;
				}
            }  
        });  
		
        mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.DIMISS_DIALOG:
					initDataPageView();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
	}
	
	
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.bt_quick_search:
			String keyWord = etSearch.getText().toString();
			if(keyWord !=null && !keyWord.equals("") ){
				ctx.getIntent().putExtra("keyWord", keyWord);
				ctx.getIntent().putExtra("type", type);
				ctx.getIntent().putExtra("FromWidgetFlag", "MemberSearchWidget");//标记从该页面跳过去
				ctx.setContentView(new MemberListWidget(ctx)); 
			}else {
				Toast.makeText(ctx, "搜索关键字不能为空", Toast.LENGTH_LONG).show();
			}
			break;
 
		case R.id.search_linearlayout_back:
//			ctx.setContentView(new HomeWidget(ctx));
			ctx.finish();
			break;
		default:
			toDetail(v.getId());
			break;
		}
		 
	}
	private void toDetail(int id) {
		int num = 0;
		switch(id) {
		case R.id.hot_res_pageview_img1:
			num += 0;
			break;
		case R.id.hot_res_pageview_img2:
			num += 1;
			break;
		case R.id.hot_res_pageview_img3:
			num += 2;
			break;
		case R.id.hot_res_pageview_img4:
			num += 3;
			break;
		case R.id.hot_res_pageview_img5:
			num += 4;
			break;
		case R.id.hot_res_pageview_img6:
			num += 5;
			break;
		}
		int position = crrentPageId*6 + num;
		User member = memberList.get(position);
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putSerializable("memeber", member);
			intent.putExtras(bundle);
			intent.setClass(ctx, MemberHomepageActivity.class);
			ctx.startActivity(intent);
	 
	}
 
	
	private void getHotMember(){
		memberList = new ArrayList<User>();
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("count",count));
				String result  = HttpUtils.Post(Global.getServlethotmember(), params);
				if (Global.DEBUG) {
					System.out.println("result:"+result);
				}
				if (result!=null) {
					parseResponse(result);
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
				
			}
		}.start();
	}
	
	
	//解析返回的结果（json）
	private void parseResponse(String result){
		JSONManager jsonManager = new JSONManager();
		boolean success = jsonManager.isGotJSONObject(result);
		if (success) {
			JSONArray jsonArray = jsonManager.getJsonList();
			for(int i=0; jsonArray != null  && i < jsonArray.length(); i++) {
				try {
					User member = new User();
					JSONObject obj = jsonArray.getJSONObject(i);
					member.setUserId(obj.getString("userid"));
					member.setUserName(obj.getString("username"));
//					member.setArea(obj.getString("areaname"));
//					member.setFans(obj.getString("fans"));
//					member.setAttention(obj.getString("attention"));
					member.setSex(obj.getString("gender"));
//					String groupId = obj.getString("groupid");
//					member.setGroupId(groupId);
//					if (groupId.equals("5")) {//达人（个人）
						member.setImgUrl(obj.getString("headicon"));
						member.setLabels(obj.getString("tags"));
						member.setInfo(obj.getString("intro"));
						member.setLevel(StringUtils.parseFloat(obj.getString("level")));
//					}else if(groupId.equals("8")) {//达人（商家）
//						member.setImgUrl(obj.getString("thumb"));
//						member.setLabels(obj.getString("catids"));
//						member.setInfo(obj.getString("keyword"));
//					}
//					member.setLevel(level)
					memberList.add(member);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	
	private void initDataPageView() {
		 
		pageViews = new ArrayList<View>();
		int pageCount = memberList.size()/6 + (memberList.size()%6 == 0?0:1);
		System.out.println("hotResPackageList.size():pageCount；"+pageCount);
		for(int i=0; i< pageCount; i++) {
			pageViews.add(inflater.inflate(R.layout.hot_member_pageview, null));
		}
		
		User member;
		
		for(int i=0; i<pageViews.size(); i++) {
			view = pageViews.get(i);
			iv1 = (ImageView)view.findViewById(R.id.hot_res_pageview_img1);
			iv2 = (ImageView)view.findViewById(R.id.hot_res_pageview_img2);
			iv3 = (ImageView)view.findViewById(R.id.hot_res_pageview_img3);
			iv4 = (ImageView)view.findViewById(R.id.hot_res_pageview_img4);
			iv5 = (ImageView)view.findViewById(R.id.hot_res_pageview_img5);
			iv6 = (ImageView)view.findViewById(R.id.hot_res_pageview_img6);
			int count = memberList.size() - (i+1)*6;
			if(count >= 0) {
				for(int j=1; j<=6; j++) {
					member = memberList.get(i*6 + j-1);
					initImage(j, member);
				}
			} else {
				count = memberList.size() - i*6;
				for(int j=1; j<=count; j++) {
					member = memberList.get(i*6 + j-1);
					initImage(j, member);
				}
				switch(count) {
				case 1:
					iv2.setVisibility(ImageView.INVISIBLE);
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 2:
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 3:
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 4:
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 5:
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				}
			}
			
		}
		
		pageAdapter = new GeneralPageAdapter(pageViews);
		viewPager.setAdapter(pageAdapter);
		viewPager.setOnPageChangeListener(new GuidePageChangeListener());
	}
	private void initImage(int id, User member) {
		switch(id) {
		case 1:
			loadImage(iv1, member.getImgUrl());
			iv1.setOnClickListener(this);
			break;
		case 2:
			loadImage(iv2, member.getImgUrl());
			iv2.setOnClickListener(this);
			break;
		case 3:
			loadImage(iv3, member.getImgUrl());
			iv3.setOnClickListener(this);
			break;
		case 4:
			loadImage(iv4, member.getImgUrl());
			iv4.setOnClickListener(this);
			break;
		case 5:
			loadImage(iv5, member.getImgUrl());
			iv5.setOnClickListener(this);
			break;
		case 6:
			loadImage(iv6, member.getImgUrl());
			iv6.setOnClickListener(this);
			break;
		}
	}
	// 指引页面更改事件监听器
	class GuidePageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int arg0) {
			crrentPageId = arg0;
			switch(arg0) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			}
		}
	}
	
 
	
	@Override
	public void notifyAdapter() {
		
	}
}
